ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Understanding HTTP Interceptors in Angular

The Angular Interceptor helps us to modify the HTTP Request by intercepting it before the Request is sent to the back end. It can also modify the incoming Response from the back end. The Interceptor globally catches every outgoing and in coming request at a single place. We can use it to add custom headers to the outgoing request, log the incoming response, etc. This guide shows you how to make use of an Angular HTTP interceptor using a few examples.

What is angular Http interceptor

The Angular HTTP interceptors sit between our application and the backend. When the application makes a request, the interceptor catches the request (HttpRequest) before it is sent to the backend. By Intercepting requests, we will get access to request headers and the body. This enables us to transform the request before sending it to the Server.

When the response (HttpResponse) arrives from the back end the Interceptors can transform it before passing it to our application.

One of the main benefits of the Http Interceptors is to add the Authorization Header to every request. We could do this manually, but that is a lot of work and error-prone. Another benefit is to catch the errors generated by the request and log them.

How to Create Http Interceptor

To Implement the Interceptor, you need to create an injectable service, which implements the HttpInterceptorinterface.

                              

@Injectable,() export class AppHttpInterceptor implements HttpInterceptor {
                            
                        

This class must implement the method Intercept.

                              

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    //do whatever you want with the HttpRequest
 
    return next.handle(req);   //invoke the next handler
}   
 
                            
                        

This class is then provided in the Root Module using the HTTP_INTERCEPTORS injection token:

                              
 
providers: [
    {
        provide: HTTP_INTERCEPTORS,
        useClass: AppHttpInterceptor,
        multi: true
    }
],
 
                            
                        

HttpInterceptor Interface

At the heart of the Interceptor, logic is the HttpInterceptor Interface. we must Implement it in our Interceptor Service.

The interface contains a single method Intercept with the following signature

                              

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
                            
                        

HttpRequest

The first argument is HttpRequest.

The HttpRequest is an outgoing HTTP request which is being intercepted. It contains URL, method, headers, body, and other request configuration.

The HttpRequest is a immutable class. Which means that we can’t modify the original request. To make changes we need to clone the Original request using the HttpRequest.clone method

HttpHandler

The second argument is httpHandler

The HttpHandler dispatches the HttpRequest to the next Handler using the method HttpHandler.handle. The next handler could be another Interceptor in the chain or the Http Backend.

Http Interceptor Example

Open the GitHubService app, which we created in the previous tutorial. You can download it from GitHub. The Final code is in the folder HttpInterceptors. The initial code in HttpGetParameters folder.

Create the Interceptor

Create AppHttpInterceptor.ts under the src/app folder and copy the following code

                              

import {Injectable} from "@angular/core";
import {HttpEvent, HttpHandler, HttpInterceptor,HttpRequest} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
 
@Injectable()
export class AppHttpInterceptor implements HttpInterceptor {
    constructor() {
    }
 
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log(req);
        return next.handle(req);
    }
}
 
                            
                        

Now let us look at each code in detail

First, we have Imported the following module.

                              

import {Injectable} from "@angular/core";
import {HttpEvent, HttpHandler, HttpInterceptor,HttpRequest} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
                            
                        

Create a class AppHttpInterceptor which implements HttpInterceptor Interface.

                              

export class AppHttpInterceptor implements HttpInterceptor {
                            
                        

Then create an Intercept method that takes HttpRequest and HttpHandler as the argument.

                              

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    //Do whatever you want to do with the Request
    console.log(req);
    return next.handle(req);
}

                            
                        

In the method body, you can modify the HttpRequest object. Once done, you can call the HttpHandler.handle method of the HttpHandler with the HttpRequest object. The HttpHandler.handle method invokes the next interceptor or sends the request to the backend server.

App.Module

The Complete code from App Module.

                              
 
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule,HTTP_INTERCEPTORS} from '@angular/common/http';
import { FormsModule } from '@angular/forms';
 
import { AppComponent } from './app.component';
 
import { GitHubService } from './github.service';
import {AppHttpInterceptor} from './AppHttpInterceptor';
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [GitHubService,
    {
    provide: HTTP_INTERCEPTORS,
    useClass: AppHttpInterceptor,
    multi: true
  }
],
  bootstrap: [AppComponent]
})
export class AppModule { }
                            
                        

First, we need to import the HttpClientModule & HTTP_INTERCEPTORS from @angular/common/http.

                              

import { HttpClientModule,HTTP_INTERCEPTORS} from '@angular/common/http';
 
                            
                        

Next, register AppHttpInterceptor as the Provider for the HTTP_INTERCEPTORS.

                              

 providers: [GitHubService,
    {
    provide: HTTP_INTERCEPTORS,
    useClass: AppHttpInterceptor,
    multi: true
  }
 
                            
                        

Run the Application. Open the developer console and see the output of console.log(req).

Setting the new headers

We are able to Intercept the request and log it to the console in the above example. Now we will modify the HTTP Headers and Custom Headers.

Adding the Content-Type

To Modify the request we need to clone it. The HttpRequest.clone method allows us to modify the specific properties of the request while copying others. In the following example we are adding the new header content-type to the request.

                              

req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
                            
                        

The headers object is also immutable. Hence we need to clone it using the headers.set method. The header.set method clones the current header and adds/modifies the new header value and returns the cloned header.

You can also use the headers.append method as shown below. Note that the append method always appends the header even if the value is already present.

                              
 
req = req.clone({ headers: req.headers.append('Content-Type', 'application/json') });
 
                            
                        

You can also make use of the setHeaders shortcut as shown below

You can also make use of the setHeaders shortcut as shown below

req = req.clone( {setHeaders: {‘Content-Type’: ‘application/json’}} );

You may want to check if the header already exists using headers.has() method.

                              
 
if (!req.headers.has('Content-Type')) {
    req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
}

 
                            
                        

Check the current value of the header.

                              

req.headers.get('Accept')
                            
                        

And remove a header.

                              

req = req.clone({ headers: req.headers.delete('Content-Type','application/json') });
                            
                        

Adding the Authorisation token

Add authorization token.

                              
 
const token: string =authService.Token; //Get token from some service
if (token) {
    req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
}
                            
                        

Intercepting the Response

The response of the back-end server can be intercepted using the various Rxjs Operators. The map can be used to modify the response before sending it to the application. The do operator is useful for logging the events or time requests. The catch operator can be used to catch the error. The retry operator can be used to retry the failed operation.

Logging

The following example code shows the use of do operator. The do operator is invoked whenever certain events take place on an Observable.

                              

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
 
        req = req.clone({ headers: req.headers.append('Content-Type', 'application/json')});
        const started = Date.now();
 
        return next.handle(req)
        .do(event => {
            console.log(event);
            const elapsed = Date.now() - started;
            console.log(`Request for ${req.urlWithParams} took ${elapsed} ms.`);
            if (event instanceof HttpResponse) {
                console.log(`Response Received`);
            };
        });
    }
 
                            
                        

In the above example, do is invoked twice. First time when the request is sent to the server (event={type: 0}). The second time when the response is received (event instanceof HttpResponse).

Modify Response

The following code shows the use of the map operator, which allows us to transform the response. The response can be modified using the method clone (the response object is immutable). Then return the cloned response. The example below replaces the entire response body with the new body and returns the response.

                              

   intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
 
        return next.handle(req)
            .map(resp => {
 
                const myBody = [{ 'id': '1',
                                  'name': 'TekTutorialsHub',
                                  'html_url': 'www.tektutorialshub.com',
                                  'description': 'description' 
                                }];
 
                // on Response
                if (resp instanceof HttpResponse) {
                    console.log(resp);
                    console.log(resp.body);
                    resp = resp.clone<any>({ body: myBody});
                    return resp;
                }
            });
    }
 
 
                            
                        

Catching the Error

The errors can be caught with the catch operator. The catch callback gets the HttpErrorResponse as its argument, which represents an error object. It contains information about headers, status, statusText & URL, etc.

                              
 
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
 
        const token: string = 'invald token';
        req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
 
        return next.handle(req)
            .map(resp => {
                // on Response
                if (resp instanceof HttpResponse) {
                    // Do whatever you want with the response.
                    return resp;
                }
            }).catch(err => {
                // onError
                console.log(err);
                if (err instanceof HttpErrorResponse) {
                    console.log(err.status);
                    console.log(err.statusText);
                    if (err.status === 401) {
                        // redirect the user to login page
                        // 401 unauthorised user
                    }
                }
                return Observable.of(err);
            });
    }
 
                            
                        

Cancel the current Request

We can also cancel the current request by returning the EMPTY observable.

The following code snippet checks if the user is logged in. If not then it will not send the request to server.

                              

import { EMPTY } from 'rxjs';
 
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  if (NotLoggedIn) {
    return EMPTY;
  }
 
  return next.handle(request);
}

                            
                        

Change the Requested URL

You can change the requested URL before it sent to the server. The HttpRequest contains the url property, which you can change before sending the request.

This is useful when you want to add the base URL of all the requests, change HTTP to HTTPS etc.

                              
const baseURL="https://www.tektutorialsHub.com/";
 
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
 
   const newReq = req.clone({
      url: baseURL + req.url;
    });
 
   return next.handle(httpsReq);
}
 
                            
                        

Summary

We learned how to intercept HTTP request & response using the new HttpClientModule. The Interceptor can be useful for adding custom headers to the outgoing request, logging the incoming response, etc.